#coding:utf-8
from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

from django.conf import settings
import MySQLdb
import json
from aliexpress.api import datelist
import datetime,time
import random
import urllib
import requests
import hashlib
from API import *
from aliexpress.models import Country,TranslateContent,ProductDeclare,StoreInfo,\
    OrderMemo,OrderDealMark,DeliveryInformation,ChooseLogistics,OrderDeal
from aliexpress.views import countryTanslate

from django.views.decorators.csrf import csrf_exempt

from django.conf import settings
from .basecon import *
from erp.models import *
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )


def getProductlibraryList(request):
    print 1
    if not request.user.is_authenticated():
        return redirect('/ucenter/login/'+"?from="+request.get_full_path())
    user = request.user

    #获取用户授权查看的店铺
    sql = 'SELECT `store_id` from `sys_store_user` WHERE `user_id`="%d"'%(user.id)
    userStores = my_custom_sql(sql)

    page = request.GET.get('page','1')
    searchTxt = request.GET.get('searchTxt',None)
    searchType = request.GET.get('searchType',None)
    goodsStock = request.GET.get('goodsStock',None)

    print 2
    if len(userStores)>0:

        sql = 'SELECT ID,IMAGE,NAME,PRODUCTWEIGHT,CHANGJIANAME,CHANGJIAURL,NOTE,CREATE_TIME FROM `e_productlibrary` '
        sql += ' WHERE USER_ID = %d '%(user.id)
        sql1='SELECT count(1) as sum from `e_productlibrary` '
        sql1 += ' WHERE USER_ID = %d ' % (user.id)
        if searchTxt:
            word = searchTxt.strip()
            word = word.replace('"','\\"')

            if searchType == '2':
                sql += 'AND `ID` like "%'+word+'%" '
                sql1 += 'AND `ID` like "%' + word + '%" '
            else:
                sql += 'AND `NAME` like "%'+word+'%" '
                sql1 += 'AND `ID` like "%' + word + '%" '
        pageSize = 30
        sql+='order by ID desc '
        sql+=' limit '+str((int(page)-1)*int(pageSize))+','+str(int(page)*int(pageSize))
        print(sql)
        temp = my_custom_sql(sql)
        totalCount=my_custom_sql(sql1)[0]["sum"]
        productData = temp
        currentPage = int(page)

        mod = divmod(int(totalCount),pageSize)

        if mod[1]>0:
            totalPage = mod[0]+1
        else:
            totalPage = mod[0]

        pageList = range(1,totalPage+1)

        pageData = []

        for pg in pageList:
            if currentPage == pg:
                active = True
            else:
                active = False
            pageData.append({"page":pg,"active":active})


    else:
        msg = '您没有被授权查看店铺的产品'
        return render(request,'aside/error.html',locals())
    return render(request, 'aside/erp/productlibrary.html', locals())

def getProductDetail(request):
    productId = request.GET.get('productId',None)
    sql = 'SELECT * FROM `e_productlibrary` where ID = '+productId
    print sql
    temp = my_custom_sql(sql)
    return HttpResponse(json.dumps(temp[0],ensure_ascii=False),content_type='application/json; charset=utf-8')




def editProductLibrary(request):
    user = request.user
    productId = request.GET.get('productId', None)
    NUMBERS = request.GET.get("NUMBERS",None)
    print NUMBERS+"*****"
    NAME = request.GET.get('NAME', None)
    CHANGJIANAME = request.GET.get('CHANGJIANAME', None)
    CHANGJIAURL = request.GET.get('CHANGJIAURL', None)
    NOTE = request.GET.get('NOTE', None)
    #修改逻辑
    if productId and productId != '0':
        sql = "update e_productlibrary set NAME='"+NAME+"',CHANGJIANAME='"+CHANGJIANAME+"',CHANGJIAURL='"+CHANGJIAURL+"',NOTE='"+NOTE+"' where ID="+productId
        temp = my_update_sql(sql)
        print sql
        data = {"status":1}
        return HttpResponse(json.dumps(data, ensure_ascii=False), content_type='application/json; charset=utf-8')
    else:
        #新增逻辑
        print(productId,NUMBERS,NAME,CHANGJIANAME,CHANGJIAURL)
        # p = Productlibrary.objects.using('erp').create(USER_ID=user.id,NUMBERS = NUMBERS,
        #                           NAME=NAME,CHANGJIANAME = CHANGJIANAME,
        #                           CHANGJIAURL = CHANGJIAURL,
        #                           NOTE=NOTE,USER_NAME = user.username
        #                           )
        p = Productlibrary()
        p.NUMBERS = NUMBERS
        p.NAME = NAME
        p.CHANGJIANAME = CHANGJIANAME
        p.CHANGJIAURL = CHANGJIAURL
        p.NOTE = NOTE
        print user.id
        p.USER_NAME = user.username
        print user.username
        p.save(using='erp')
        data = {"status": 1}
        return HttpResponse(json.dumps(data, ensure_ascii=False), content_type='application/json; charset=utf-8')

def delProductLibrary(request):
    productId = request.GET.get('productId', None)
    Productlibrary.objects.using('erp').filter(ID=productId).delete()
    data = {"status": 1}
    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type='application/json; charset=utf-8')